package com.timothy.business.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.timothy.business.constant.ResultStatusEnum;
import com.timothy.business.model.ResultMessage;
import com.timothy.business.util.PasswordHelper;
import com.timothy.business.util.ResultMessageHelper;

@RestController
@RequestMapping("/sys")
public class HomeController {

	@RequestMapping(value = "/login")
	public ResultMessage<Object> login(String phone, String password) {
		if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
			return ResultMessageHelper.failResult(ResultStatusEnum.BAD_REQUEST, "用户名或密码错误！");
		}
		// 用手机号做盐值
		String encryptPassword = PasswordHelper.encryptPassword(password, phone);
		UsernamePasswordToken token = new UsernamePasswordToken(phone, encryptPassword);
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
		} catch (AuthenticationException e) {
			token.clear();
			return ResultMessageHelper.failResult(ResultStatusEnum.BAD_REQUEST, "用户名或密码错误！");
		}
		return ResultMessageHelper.successResult();
	}

	@RequestMapping(value = "/logout")
	public ResultMessage<Object> logout() {
		SecurityUtils.getSubject().logout();
		return ResultMessageHelper.successResult();
	}
}
